package com.yunquan.ohana.ui.calendar.event.adapter

import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.yunquan.ohana.ui.calendar.event.EventActivity
import com.yunquan.ohana.ui.calendar.event.month.EventMonthFragment
import com.yunquan.ohana.ui.calendar.event.week.EventWeekFragment

class EventPagerAdapter(
    ac: EventActivity,
    val isWeek: Boolean,
    val deviceId: String,
    val userType: Boolean,
) : FragmentStateAdapter(ac) {

    private val LOOP_COUNT = Int.MAX_VALUE
    private val BASE_POSITION = LOOP_COUNT / 2  // 启动居中位置
    private var modeVersion: Long = 0L
    val basePosition: Int
        get() = BASE_POSITION

    private val fragmentMap = mutableMapOf<Int, Fragment>()

    override fun getItemCount(): Int = LOOP_COUNT

    /** 获取当前下标对应的 Fragment（如果存在） */
    fun getFragment(position: Int): Fragment? = fragmentMap[position]

    /** 可选：清理无效的 fragment */
    fun removeFragment(position: Int) {
        fragmentMap.remove(position)
    }

    /**
     * 当显示模式（周/月）发生变化时调用，递增版本以使 FragmentStateAdapter 认为所有 itemId 变化，从而销毁并重建当前与缓存页。
     */
    fun onModeChanged() {
        modeVersion++
        notifyDataSetChanged()
    }

    override fun getItemId(position: Int): Long {
        // 组合模式版本与位置，保证模式切换后 itemId 全部变化
        return modeVersion * LOOP_COUNT + position.toLong()
    }

    override fun containsItem(itemId: Long): Boolean {
        // 仅当前模式版本范围内的 itemId 被视为有效，触发旧 Fragment 移除
        val start = modeVersion * LOOP_COUNT
        val end = start + LOOP_COUNT - 1
        return itemId in start..end
    }

    override fun createFragment(position: Int): Fragment {
        val offset = position - BASE_POSITION
        val fragment = if (isWeek) {
            EventWeekFragment.newInstance(deviceId,userType, offset)
        } else {
            EventMonthFragment.newInstance(deviceId,userType, offset)
        }
        fragmentMap[position] = fragment
        return fragment
    }
}